package com.mall.filter;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Simple filter that prints a report on the standard output each time an
 * associated servlet or JSP page is accessed.
 */

public class SessionFilter implements javax.servlet.Filter
{

	String timeoutURL =null;
	List<String> noCheckURLList = new ArrayList<String>();
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws ServletException, IOException
	{

		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse= (HttpServletResponse) response;
		HttpSession session = httpServletRequest.getSession();
		//session超时，且非登录时
		if(session == null)
		{
			httpServletResponse.sendRedirect(httpServletRequest.getContextPath()  +"/"+timeoutURL );
			return;
		}
		else 
		{
			//session中没有记录用户，判定为非法登录
			Object operator = session.getAttribute("operator");
			
			if(operator == null && !checkRequestURIIsNotCheck(httpServletRequest))
			{
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath()  +"/"+timeoutURL );
				return;
			}
		}
		
		
		chain.doFilter(request, response);

	}

	public void init(FilterConfig config) throws ServletException
	{
		timeoutURL= config.getInitParameter("timeout");
		String notCheckURLListStr = config.getInitParameter("noCheckURLList");
		
		if(notCheckURLListStr != null){
			StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";"); 
			noCheckURLList.clear(); 
			
			while(st.hasMoreTokens()){
				noCheckURLList.add(st.nextToken()); 
			} 
		}
		
	}

	public void destroy()
	{
		// TODO Auto-generated method stub
		noCheckURLList.clear(); 
	}
	
	private boolean checkRequestURIIsNotCheck(HttpServletRequest request){
		if(request.getServletPath().endsWith(".jsp") || request.getServletPath().endsWith(".do"))
		{
			String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
			String type = request.getParameter("type");
			if(type!=null &&(type.equals("login") || type.equals("logout")))
			{
				return true;
			}
			
			return noCheckURLList.contains(uri);
		}
		
		return true;
		
	}

	

}
